package com.example.aiinterview.service.impl;

import com.example.aiinterview.service.AIService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class AIServiceImpl implements AIService {

    private final WebClient webClient;

    @Value("${deepseek.api.api-key}")
    private String apiKey;

    @Override
    public List<String> generateInterviewQuestions(String prompt) {
        String response = callDeepSeekApi(prompt);
        return parseQuestions(response);
    }

    @Override
    public String evaluateAnswer(String prompt) {
        return callDeepSeekApi(prompt);
    }

    @Override
    public String generateFinalFeedback(String prompt) {
        return callDeepSeekApi(prompt);
    }

    @Override
    public String generateResponse(String prompt) {
        return callDeepSeekApi(prompt);
    }

    private String callDeepSeekApi(String prompt) {
        // 检查API密钥
        if (apiKey == null || apiKey.trim().isEmpty() || apiKey.equals("your-api-key-here")) {
            System.out.println("⚠️ API密钥未配置，使用默认响应");
            return "请介绍一下您的工作经验";
        }

        Map<String, Object> requestBody = Map.of(
                "model", "deepseek-chat",
                "messages", List.of(
                        Map.of(
                                "role", "user",
                                "content", prompt
                        )
                ),
                "temperature", 0.7,
                "max_tokens", 1000
        );

        try {
            System.out.println("正在调用DeepSeek API，API密钥: " + (apiKey != null ? apiKey.substring(0, Math.min(10, apiKey.length())) + "..." : "null"));

            return webClient.post()
                    .contentType(MediaType.APPLICATION_JSON)
                    .header("Authorization", "Bearer " + apiKey)
                    .bodyValue(requestBody)
                    .retrieve()
                    .bodyToMono(Map.class)
                    .map(response -> {
                        try {
                            System.out.println("API响应: " + response);

                            // 检查是否有错误
                            if (response.containsKey("error")) {
                                @SuppressWarnings("unchecked")
                                Map<String, Object> error = (Map<String, Object>) response.get("error");
                                return "API错误: " + error.get("message");
                            }

                            @SuppressWarnings("unchecked")
                            List<Map<String, Object>> choices = (List<Map<String, Object>>) response.get("choices");
                            if (choices != null && !choices.isEmpty()) {
                                @SuppressWarnings("unchecked")
                                Map<String, Object> message = (Map<String, Object>) choices.get(0).get("message");
                                Object content = message.get("content");
                                return content != null ? content.toString() : "AI服务未返回有效内容";
                            }
                            return "AI服务未返回有效响应";
                        } catch (Exception e) {
                            System.err.println("解析AI响应时发生错误: " + e.getMessage());
                            e.printStackTrace();
                            return "解析AI响应时发生错误: " + e.getMessage();
                        }
                    })
                    .onErrorReturn("调用AI服务时发生错误")
                    .block(Duration.ofSeconds(35)); // 与WebClient超时保持一致（留出余量）
        } catch (Exception e) {
            System.err.println("调用AI服务时发生异常: " + e.getMessage());
            e.printStackTrace();
            return "调用AI服务时发生错误: " + e.getMessage();
        }
    }


    private List<String> parseQuestions(String response) {
        List<String> questions = new ArrayList<>();
        String[] lines = response.split("\n");

        for (String line : lines) {
            String trimmedLine = line.trim();
            if (!trimmedLine.isEmpty()) {
                // Remove any numbering if present
                trimmedLine = trimmedLine.replaceAll("^\\d+\\.\\s*", "");
                questions.add(trimmedLine);
            }
        }

        return questions;
    }
}
